$(function () {
  Number.prototype.padZero = function () {
    return String.prototype.padStart.call(this, 2, "0");
  };
  template.defaults.imports.dataFormat = function (data) {
    const dt = new Date(data);

    const n = dt.getFullYear();
    const y = (dt.getMonth() + 1).padZero();
    const r = dt.getDate().padZero();

    const s = dt.getHours().padZero();
    const f = dt.getMinutes().padZero();
    const m = dt.getSeconds().padZero();

    return n + "-" + y + "-" + r + "  " + s + ":" + f + ":" + m;
  };
  const { layer, form, laypage } = layui;
 let q = {
    pagenum: 1,
    pagesize: 2,
    cate_id: "",
    state: "",
  };
  initTable();
  initCate();
  function initTable() {
    $.ajax({
      method: "GET",
      url: "/my/article/list",
      data: q,
      success: function (res) {
        if (res.status !== 0) {
          return layer.msg("获取文章列表失败！");
        }
        // 使用模板引擎渲染页面的数据
        let htmlStr = template("tpl-table", res);
        $("tbody").html(htmlStr);
        renderPage(res.total);
      },
    });
  }


  function initCate() {
    $.ajax({
      method: "GET",
      url: "/my/article/cates",
      success: function (res) {
        if (res.status !== 0) return layer.msg("获取失败");
        const html = template("tpl-cate", res);
        $("[name=cate_id]").html(html);
        form.render();
      },
    });
  }
  $("#form-search").on("submit", function (e) {
    e.prototype();
    let cate_id = $("[name=cate_id]").val();
    let state = $(["name=state"]).val();

    q.cate_id = cate_id;
    q.state = state;

    initTable();
  });
  // 定义渲染分页的方法
  function renderPage(total) {
    // console.log(total);
    laypage.render({
      elem: "pageBox",
      count: total,
      limit: q.pagesize,
      curr: q.pagenum,
      layout: ["count", "limit", "prev", "page", "next", "skip"],
      limits: [2, 3, 5, 10],
      jump: function (obj, first) {
        q.pagenum = obj.curr;
        q.pagesize = obj.limit;
        if (!first) {
          initTable();
        }
      },
    });
  }
  $("tbody").on("click", ".btn-delete", function () {
    const len = $('.btn-delete').length;
    console.log(len);
    const id = $(this).data('id');
    layer.confirm("确认删除?", { icon: 3, title: "提示" }, function (index) {
      $.ajax({
        method: "GET",
        url: "/my/article/delete/" + id,
        success: function (res) {
          if (res.status !== 0) return layer.msg("删除文章失败");
          layer.msg("删除文章成功");
          if(len === 1 && q.pagenum > 1 ){
            q.pagenum--;
          }
          initTable();
        },
      });
      layer.close(index);
    });
  });
});
